package com.ht.medicaltreatment.view

import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import androidx.core.view.marginLeft
import androidx.core.view.marginTop
import com.ht.medicaltreatment.R

class ProgressBarSampleCollection
@JvmOverloads constructor(context: Context,attributes: AttributeSet? = null,style:Int = -1)
    :View(context,attributes,style) {
    private var mProgress = 0.0f
    private var maxValue = 100f
    private var rectf:RectF
    private var mPaintBg:Paint
    private var mPaintProgress:Paint
    private var mViewTop = 0
    private var mViewLeft = 0
    private var mViewWidth = 0
    private var mViewHeight = 0
    private var canvasBitmap = false
    init {
        mPaintBg = Paint()
        mPaintBg.isAntiAlias = true
        mPaintBg.style = Paint.Style.FILL
        mPaintBg.color = getContext().getColor(R.color.progressBg)
        mPaintBg.strokeCap = Paint.Cap.ROUND
        mPaintBg.strokeWidth = 10f
        rectf = RectF()

        mPaintProgress = Paint()
        mPaintProgress.isAntiAlias = true
        mPaintProgress.style = Paint.Style.FILL
        mPaintProgress.color = getContext().getColor(R.color.progress)
        mPaintProgress.strokeCap = Paint.Cap.ROUND
        mPaintProgress.strokeWidth = 10f
        rectf = RectF()
    }

    fun setMaxProgress(maxValue:Float){
        this.maxValue = maxValue
    }

    fun setProgress(_progress:Float){
        var progress = _progress
        if(progress > maxValue){
            progress = maxValue
        }
        mProgress = progress/maxValue
        invalidate()
    }

    lateinit var view:View

    override fun onFinishInflate() {
        super.onFinishInflate()
        view = findViewById<ProgressBarSampleCollection>(R.id.progress)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mViewLeft = view.marginLeft
        mViewTop = view.marginTop
        mViewWidth = view.measuredWidth
        mViewHeight = view.measuredHeight
    }

    override fun onDraw(canvas: Canvas?) {
        rectf.top = 0f
        rectf.left = mViewWidth*mProgress
        rectf.bottom = mViewHeight.toFloat()
        rectf.right = mViewWidth.toFloat()

        //背景
        canvas?.drawRoundRect(
            0f,
            0f,
            mViewWidth.toFloat(),
            mViewHeight.toFloat(),
            (mViewWidth/2).toFloat(),
            (mViewWidth/2).toFloat(),mPaintBg)
        //进度
        canvas?.drawRoundRect(rectf, (mViewWidth/2).toFloat(),(mViewWidth/2).toFloat(),mPaintProgress)
    }
}